package com.xx.account.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.xx.account.domain.AccountBoss;
import com.xx.account.domain.AccountSendLeaflet;
import com.xx.account.mapper.AccountBossMapper;
import com.xx.account.mapper.AccountSendLeafletMapper;
import com.xx.common.utils.DateUtils;
import com.xx.common.utils.SecurityUtils;
import com.xx.common.utils.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.xx.account.mapper.AccountRecordMapper;
import com.xx.account.domain.AccountRecord;
import com.xx.account.service.IAccountRecordService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 接单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-28
 */
@Service
public class AccountRecordServiceImpl implements IAccountRecordService
{
    @Resource
    private AccountRecordMapper accountRecordMapper;

    @Resource
    private AccountBossMapper accountBossMapper;

    @Resource
    private AccountSendLeafletMapper accountSendLeafletMapper;

    /**
     * 查询接单
     *
     * @param id 接单主键
     * @return 接单
     */
    @Override
    public AccountRecord selectAccountRecordById(String id)
    {
        return accountRecordMapper.selectAccountRecordById(id);
    }

    /**
     * 查询接单列表
     *
     * @param accountRecord 接单
     * @return 接单
     */
    @Override
    public List<AccountRecord> selectAccountRecordList(AccountRecord accountRecord)
    {
        accountRecord.setCreateBy(SecurityUtils.getUserId().toString());

        List<AccountRecord> list = accountRecordMapper.selectAccountRecordList(accountRecord);
        // 计算价格
        for (AccountRecord record : list) {
            // 接单数量
            BigDecimal count = new BigDecimal(record.getCount());
            // 接单金额
            BigDecimal price = record.getPrice();
            // 接单合计金额
            record.setBossPriceSum(price.multiply(count));
            // 放单合计金额
            BigDecimal workerPriceSum = BigDecimal.ZERO;
            List<AccountSendLeaflet> accountSendLeafletList = accountSendLeafletMapper.selectAllAccountSendLeafletByRecordId(record.getId());
            for (AccountSendLeaflet accountSendLeaflet : accountSendLeafletList) {
                BigDecimal bossPirce = accountSendLeaflet.getPrice().multiply(new BigDecimal(accountSendLeaflet.getCount()));
                workerPriceSum = workerPriceSum.add(bossPirce);
            }
            record.setWorkerPriceSum(workerPriceSum);
            // 剩余金额
            record.setOverPrice(record.getBossPriceSum().subtract(record.getWorkerPriceSum()));
        }
        return list;
    }

    /**
     * 新增接单
     *
     * @param accountRecord 接单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertAccountRecord(AccountRecord accountRecord)
    {
        accountRecord.setId(UUID.randomUUID().toString().replaceAll("-",""));
        accountRecord.setCreateTime(DateUtils.getNowDate());
        accountRecord.setCreateBy(SecurityUtils.getUserId().toString());
        accountRecord.setIsSuccess(1);

        int rows = accountRecordMapper.insertAccountRecord(accountRecord);

        // 老板操作数+1 并 更新最后使用时间
        AccountBoss accountBoss = accountBossMapper.selectAccountBossById(accountRecord.getBossId());
        accountBoss.setCount(accountBoss.getCount() + 1);
        accountBoss.setEndTime(DateUtils.getNowDate());
        accountBossMapper.updateAccountBoss(accountBoss);
        return rows;
    }

    /**
     * 修改接单
     *
     * @param accountRecord 接单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateAccountRecord(AccountRecord accountRecord)
    {
        return accountRecordMapper.updateAccountRecord(accountRecord);
    }

    /**
     * 批量删除接单
     *
     * @param ids 需要删除的接单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteAccountRecordByIds(String[] ids)
    {
        return accountRecordMapper.deleteAccountRecordByIds(ids);
    }

    /**
     * 删除接单信息
     *
     * @param id 接单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteAccountRecordById(String id)
    {
        return accountRecordMapper.deleteAccountRecordById(id);
    }

    /**
     * 修改交单状态
     *
     * @param accountRecord
     * @return
     */
    @Override
    public int switchIsSuccess(AccountRecord accountRecord) {
        AccountRecord old = accountRecordMapper.selectAccountRecordById(accountRecord.getId());
        // 如果交单状态设置为1（未交单）清空交单时间
        if(accountRecord.getIsSuccess() == 1) {
            old.setSuccessTime(null);
        }else {
            old.setSuccessTime(DateUtils.getNowDate());
        }
        old.setIsSuccess(accountRecord.getIsSuccess());
        return accountRecordMapper.updateAccountRecord(old);
    }

    @Override
    public void export(HttpServletResponse response, AccountRecord accountRecord) {
        Workbook workbook = new XSSFWorkbook();
        // 创建单元格样式
        CellStyle style = null;
        // 查询得到指定时间段下单过的老板
        accountRecord.setCreateBy(SecurityUtils.getUserId().toString());
        List<String> bossIds = accountRecordMapper.selectBossIdsByOrderTimeBetween(accountRecord);
        for (int i = 0; i < bossIds.size(); i++) {
            // 查询老板今天所有的下单信息
            accountRecord.setBossId(bossIds.get(i));
            List<AccountRecord> accountRecordList = accountRecordMapper.selectAccountRecordListByBossId(accountRecord);
            String bossName = accountRecordList.get(0).getBossName();
            //设置新的sheet页
            Sheet sheet = workbook.createSheet("【" + bossName + "】");
            sheet.setColumnWidth(0, 5120);
            //构建表头
            Row header = sheet.createRow(0);
            Cell cell = null;
            List<String> columnList = new ArrayList<>();
            columnList.add("老板名称");
            columnList.add("活动名称");
            columnList.add("活动链接");
            columnList.add("接单单价");
            columnList.add("接单数量");
            columnList.add("合计金额");
            columnList.add("接单时间");
            columnList.add("是否交单");
            for (int k = 0; k < columnList.size(); k++) {
                style = createStyle(workbook.createCellStyle(), 0);
                addCellToRow(header, k, columnList.get(k), style);
                if(k == 1 || k == 2){
                    sheet.setColumnWidth(k, (int) (5120 * 1.5));
                }else {
                    sheet.setColumnWidth(k, 5120);
                }
                sheet.setDefaultRowHeightInPoints(30);
            }

            BigDecimal overSum = BigDecimal.ZERO;
            for (int j = 1; j <= accountRecordList.size(); j++) {
                Row row = sheet.createRow(j);
                Cell rowCell = row.createCell(j);
                style = createStyle(workbook.createCellStyle(), j);
                rowCell.setCellStyle(style);
                AccountRecord ac = accountRecordList.get(j - 1);
                addCellToRow(row, 0, bossName, style);
                addCellToRow(row, 1, ac.getName(), style);
                addCellToRow(row, 2, StringUtils.isEmpty(ac.getUrl()) ? "" : ac.getUrl(), style);
                addCellToRow(row, 3, ac.getPrice().toString(), style);
                addCellToRow(row, 4, String.valueOf(ac.getCount()), style);
                BigDecimal orderPriceSum = ac.getPrice().multiply(new BigDecimal(ac.getCount()));
                addCellToRow(row, 5, orderPriceSum.toString(), style);
                addCellToRow(row, 6, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ac.getOrderTime()), style);
                addCellToRow(row, 7, ac.getIsSuccess() == 0 ? "已交单" : "未交单", style);
                overSum = overSum.add(orderPriceSum);
            }
            CellStyle totalStyle = getCellStyle(workbook);
            Font font = workbook.createFont();
            font.setColor(Font.COLOR_RED); // 设置字体颜色为红色
            font.setFontName("宋体"); // 设置字体为宋体
            font.setBold(true); // 设置加粗
            totalStyle.setFont(font);

            // 设置背景颜色为灰色
            totalStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
            totalStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置填充为实心颜色

            // 创建行和单元格
            Row row = sheet.createRow(accountRecordList.size() + 1);
            Cell total = row.createCell(4);
            Cell sum = row.createCell(5);

            // 设置单元格内容
            total.setCellValue("总计金额");
            sum.setCellValue(overSum.toString());

            // 设置单元格样式
            total.setCellStyle(totalStyle);
            sum.setCellStyle(totalStyle);

        }

        // 写入response的输出流
        try(OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private CellStyle createStyle(CellStyle style, int rowNum) {
        // 创建一个单元格样式
        style.setWrapText(true); // 自动换行
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中对齐
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中对齐
        style.setBorderTop(BorderStyle.THIN); // 上边框细线
        style.setBorderBottom(BorderStyle.THIN); // 下边框细线
        style.setBorderLeft(BorderStyle.THIN); // 左边框细线
        style.setBorderRight(BorderStyle.THIN); // 右边框细线
        // 设置底色为浅橙色 (RGB: 255, 184, 77)
        if(rowNum == 0) {
            style.setFillForegroundColor(IndexedColors.GOLD.getIndex()); // 黄色
        }else if(rowNum % 2 == 0){
            style.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex()); // 浅橙色
        }else{
            style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); // 浅橙色
        }
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return style;
    }

    @Override

    public void exportByWorker(HttpServletResponse response, AccountRecord accountRecord) {
        Workbook workbook = new XSSFWorkbook();
        // 创建单元格样式
        CellStyle style = getCellStyle(workbook);
        CellStyle rowStyle = getCellStyle(workbook);
        Font font = workbook.createFont();
        font.setColor(Font.COLOR_NORMAL);
        font.setFontName("宋体");
        font.setBold(true);
        style.setFont(font);
        accountRecord.setCreateBy(SecurityUtils.getUserId().toString());
        List<Map<String, Object>> list = accountRecordMapper.selectWorkerList(accountRecord);
        // 使用Stream API进行分组操作，按name分组
        Map<String, List<Map<String, Object>>> groupedByName = list.stream()
                .collect(Collectors.groupingBy(map -> (String) map.get("workerName"),
                        // 对每个分组的List进行排序，按orderTime正序排序
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                groupList -> {
                                    // 确保 orderTime 是 LocalDateTime 类型，并进行比较排序
                                    groupList.sort(Comparator.comparing(map -> (LocalDateTime) map.get("orderTime")));
                                    return groupList;
                                }
                        )));
        // 根据分组后的投手数据，封装excel表格
        for (String key : groupedByName.keySet()) {
            List<Map<String, Object>> maps = groupedByName.get(key);
            //设置新的sheet页
            Sheet sheet = workbook.createSheet("【" + maps.get(0).get("workerName") + "】");
            sheet.setColumnWidth(0, 5120);
            //构建表头
            Row header = sheet.createRow(0);
            Cell cell = null;
            List<String> columnList = new ArrayList<>();
            columnList.add("投手名称");
            columnList.add("活动名称");
            columnList.add("活动链接");
            columnList.add("放单单价");
            columnList.add("放单数量");
            columnList.add("合计金额");
            columnList.add("放单时间");
            for (int k = 0; k < columnList.size(); k++) {
                cell = header.createCell(k);
                addCellToRow(header, k, columnList.get(k), style);
                cell.setCellStyle(style);
                sheet.setColumnWidth(k, 5120);
            }
            BigDecimal overSum = BigDecimal.ZERO;
            int i = 1;
            for (Map<String, Object> map : maps) {
                Row row = sheet.createRow(i);
                Cell rowCell = row.createCell(i);
                rowCell.setCellStyle(rowStyle);
                addCellToRow(row, 0, map.get("workerName").toString(), rowStyle);
                addCellToRow(row, 1, map.get("name").toString(), rowStyle);
                addCellToRow(row, 2, !map.containsKey("url") ? "" : map.get("url").toString(), rowStyle);
                addCellToRow(row, 3, map.get("price").toString(), rowStyle);
                addCellToRow(row, 4, map.get("count").toString(), rowStyle);
                BigDecimal price = new BigDecimal((String) map.get("price"));
                BigDecimal orderPriceSum = price.multiply(new BigDecimal(map.get("count").toString()));
                addCellToRow(row, 5, orderPriceSum.toString(), rowStyle);
                addCellToRow(row, 6, map.get("orderTime").toString().replaceAll("T", " "), rowStyle);
                overSum = overSum.add(orderPriceSum);
                i++;
            }
            CellStyle totalStyle = getCellStyle(workbook);
            font = workbook.createFont();
            font.setFontName("宋体");
            font.setBold(true);
            font.setColor(Font.COLOR_RED);
            totalStyle.setFont(font);
            // 最后设置总金额
            Row row = sheet.createRow(i);
            Cell total = row.createCell(4);
            Cell sum = row.createCell(5);
            total.setCellValue("总计金额");
            sum.setCellValue(overSum.toString());
            total.setCellStyle(totalStyle);
            sum.setCellStyle(totalStyle);
        }
        // 写入response的输出流
        try(OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void addCellToRow(Row row, int index, String value, CellStyle style) {
        Cell cell = row.createCell(index);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }

    @Override
    public Map<String, Object> listDataSum(AccountRecord accountRecord) {
        accountRecord.setCreateBy(SecurityUtils.getUserId().toString());

        BigDecimal bossPriceSum = BigDecimal.ZERO;
        BigDecimal workerPriceSum = BigDecimal.ZERO;
        BigDecimal overPriceSum = BigDecimal.ZERO;

        // 查询接单总金额
        List<AccountRecord> accountRecords = accountRecordMapper.selectAccountRecordList(accountRecord);
        for (AccountRecord record : accountRecords) {
            // 计算接单总金额 (bossPriceSum)
            bossPriceSum = bossPriceSum.add(record.getPrice().multiply(new BigDecimal(record.getCount())));
        }

        // 查询放单总金额
        for (AccountRecord record : accountRecords) {
            List<AccountSendLeaflet> accountSendLeaflets = accountSendLeafletMapper.selectAllAccountSendLeafletByRecordId(record.getId());
            for (AccountSendLeaflet accountSendLeaflet : accountSendLeaflets) {
                workerPriceSum = workerPriceSum.add(accountSendLeaflet.getPrice().multiply(new BigDecimal(accountSendLeaflet.getCount())));
            }
        }

        // 计算结余金额 (overPriceSum = bossPriceSum - workerPriceSum)
        overPriceSum = bossPriceSum.subtract(workerPriceSum);

        // 创建返回的 Map
        Map<String, Object> map = new HashMap<>();
        map.put("bossPriceSum", bossPriceSum);
        map.put("workerPriceSum", workerPriceSum);
        map.put("overPriceSum", overPriceSum);
        return map;
    }

    private static CellStyle getCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setWrapText(true); // 自动换行
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中对齐
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中对齐
        style.setBorderTop(BorderStyle.THIN); // 上边框细线
        style.setBorderBottom(BorderStyle.THIN); // 下边框细线
        style.setBorderLeft(BorderStyle.THIN); // 左边框细线
        style.setBorderRight(BorderStyle.THIN); // 右边框细线
        return style;
    }

}
